package library.service;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import library.service.impl.BookServiceImpl;
import library.service.impl.UserServiceImpl;

public class ServiceLocatorImpl extends ServiceLocator {

    private static final Map<Class<? extends Service>, Class<? extends Service>> services = new ConcurrentHashMap<Class<? extends Service>, Class<? extends Service>>();


    static {
        services.put(UserService.class, UserServiceImpl.class);
        services.put(BookService.class, BookServiceImpl.class);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <Type extends Service> Type getService(Class<Type> key) {
        Class<? extends Service> value = services.get(key);
        if (value != null) {
            try {
                ClassLoader classLoader = value.getClassLoader();
                Class<?>[] interfaces = {key};
                Service service = value.newInstance();
                InvocationHandler handler = new ServiceInvocationHandlerImpl(service);
                return (Type) Proxy.newProxyInstance(classLoader, interfaces,
                        handler);
            } catch (Exception e) {
            }
        }
        return null;
    }
}